<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="demo">
        搜索用户名：<input type="text" name="searchName" placeholder="搜索指定用户名" v-model = searchName>
        <ul>
            <li v-for="(p,index) in fPersons" :key="index">
               {{index}} --  {{p.id}} -- {{p.name}} -- {{p.age}}
            </li>
        </ul>
        <button @click="sortByAge(1)">年龄升序</button>
        <button @click="sortByAge(2)">年龄降序</button>
        <button @click="sortByAge(0)">原本顺序</button>
    </div>
</body>
<script src="../../public/vue.dev.js"></script>
<script>
    new Vue({
        el:'#demo',
        data:{
            sortType:0,
            searchName:'',
            persons:[
                {id:1,'name':'Tom',age:13},
                {id:2,'name':'Jack',age:12},
                {id:3,'name':'Bob',age:17},
                {id:4,'name':'Cat',age:14},
                {id:5,'name':'Mike',age:14},
                {id:6,'name':'Monica',age:16},
            ],
        },
        methods:{
            sortByAge(sortType){
                this.sortType = sortType;
            }
        },
        computed:{
            fPersons(){
                let {searchName,persons,sortType} = this;
                persons = persons.filter(p=>p.name.indexOf(searchName)!=-1);
                // alert(sortType);
                if (sortType != 0) {
                    persons = persons.sort(function (p1,p2) {
                        if (sortType == 1) {
                            return p1.age - p2.age;
                        } else {
                            return p2.age - p1.age;
                        }
                    });
                }
                return persons;
            }
        }
    });

    /**
     * tips: 注意html里面绑定的数据只能写在data{} 里面
     * vm--> el + data{} + computed{} + methods{}
     *
     * 绑定事件的test(val) 要注意val的数据类型 加不加引号 否则有可能不会解析
     *
     * */
</script>
</html>
